﻿using System;
using System.Collections.Generic;
using System.Text;
using com.lover.astd.common.logic;
using com.lover.astd.common.model.enumer;

namespace com.lover.astd.common.logicexe.battle
{
    public class BattleExe : ExeBase
    {
        public BattleExe() { _name = ConfigStrings.S_Battle; _readable = ConfigStrings.SR_Battle; }
        public override void init_data()
        {
            List<int> pids = new List<int>();
            pids.Add(1);
            ServiceFactory.getBattleManager().getAllPowerInfo(_proto, _logger, _user, pids);
            refreshUi();
        }
        public override long execute()
        {
            BattleMgr mgr = ServiceFactory.getBattleManager();
            // 如果是兵器活动, 那么立刻领取免费强攻令
            if (_user.isActivityRunning(ActivityType.WeaponEvent) && !_user._battle_got_weapon_event_free_token)
            {
                mgr.getWeaponEventInfo(_proto, _logger, _user);
            }
            int result = ServiceFactory.getTroopManager().makeSureForce(_proto, _logger);
            if (result != 0)
            {
                logInfo("征兵失败, 暂停征战至下个半小时");
                return next_halfhour();
            }
            Dictionary<string, string> conf = getConfig();

            bool npc_enabled = conf.ContainsKey(ConfigStrings.npc_enabled) && conf[ConfigStrings.npc_enabled].ToLower().Equals("true");
            // 然后再看其他情况
            int npc_reserve_token = 0;
            if (conf.ContainsKey(ConfigStrings.npc_reserve_token) && conf[ConfigStrings.npc_reserve_token] != "")
                Int32.TryParse(conf[ConfigStrings.npc_reserve_token], out npc_reserve_token);
            string npcid = "";
            if (conf.ContainsKey(ConfigStrings.npc_ids) && conf[ConfigStrings.npc_ids] != "") npcid = conf[ConfigStrings.npc_ids];
            string npc_force_id = "";
            if (conf.ContainsKey(ConfigStrings.npc_force_ids) && conf[ConfigStrings.npc_force_ids] != "") npc_force_id = conf[ConfigStrings.npc_force_ids];

            bool army_enabled = conf.ContainsKey(ConfigStrings.army_enabled) && conf[ConfigStrings.army_enabled].ToLower().Equals("true");
            int army_reserve_token = 0;
            if (conf.ContainsKey(ConfigStrings.army_reserve_token) && conf[ConfigStrings.army_reserve_token] != "")
                Int32.TryParse(conf[ConfigStrings.army_reserve_token], out army_reserve_token);
            string[] armyids = new string[0], first_army_ids = new string[0];
            if (conf.ContainsKey(ConfigStrings.army_ids) && conf[ConfigStrings.army_ids] != "") armyids = conf[ConfigStrings.army_ids].Split(',');
            if (conf.ContainsKey(ConfigStrings.first_army_ids) && conf[ConfigStrings.first_army_ids] != "") first_army_ids = conf[ConfigStrings.first_army_ids].Split(',');

            bool attack_army_only_jingyingtime = conf.ContainsKey(ConfigStrings.attack_army_only_jingyingtime) && conf[ConfigStrings.attack_army_only_jingyingtime].ToLower().Equals("true");
            bool attack_first_army = conf.ContainsKey(ConfigStrings.attack_first) && conf[ConfigStrings.attack_first].ToLower().Equals("true");
            int attack_first_interval = 0;
            if (conf.ContainsKey(ConfigStrings.attack_first_interval) && conf[ConfigStrings.attack_first_interval] != "")
                Int32.TryParse(conf[ConfigStrings.attack_first_interval], out attack_first_interval);

            bool defense_enabled = conf.ContainsKey(ConfigStrings.enabled) && conf[ConfigStrings.enabled].ToLower().Equals("true");

            if (!npc_enabled && !army_enabled && !defense_enabled) return next_halfhour();

            // 看是否军令已经CD
            if (_user.TokenCdFlag && _user.TokenCdTime > 2000) return _user.TokenCdTime;
            if (_user.Token <= 0) return next_hour();

            // 看是否已经加入了队伍
            if (_user._battle_current_army_id != "")
            {
                int find_result = mgr.tryFindArmy(_proto, _logger, _user, _user._battle_current_army_id, false);
                if (find_result == 0) return immediate();
            }

            string formation = mgr.getFormation(_proto, _logger);
            bool solved = false;
            int total_token = _user.Token;
            if (npcid.Length > 0 || npc_force_id.Length > 0 || armyids.Length > 0)
            {
                if (army_enabled)
                {
                    if (armyids.Length > 0 && total_token > army_reserve_token) // first check army
                    {
                        if (!attack_army_only_jingyingtime || inJingyingArmyTime())
                        {
                            // search for troops
                            foreach (string armyid in armyids)
                            {
                                if (armyid == "") continue;
                                string[] subs = armyid.Split(':');
                                if (subs.Length < 2) continue;
                                int join_result = mgr.tryFindArmy(_proto, _logger, _user, subs[0], false);
                                if (join_result == 0)
                                {
                                    solved = true; break;
                                }
                                else if (join_result == 1) return 60 * 1000; // http error, 1分钟后继续
                                else if (join_result == 2)
                                {
                                    if (_user.TokenCdTime > 0) return _user.TokenCdTime;
                                    else return 10 * 60 * 1000; // 军令已经冷却
                                }
                                else if (join_result == 3) return next_hour(); // 没令了
                            }
                        }
                    }
                }

                if (!solved)
                {
                    if (npc_enabled)
                    {
                        if ((npcid.Length > 0 || npc_force_id.Length > 0) &&
                            (total_token > npc_reserve_token || (_user._battle_extra_npc_id > 0 && _user._battle_extra_npc_remains > 0 && total_token > 0))) // then check npc
                        {
                            int attack_result = 0;
                            string last_formation = formation;
                            // attack npcs
                            string target_npc_id = "", target_npc_formation = "";
                            mgr.getBattleInfo(_proto, _logger, _user);
                            string normal_npc_id = "", normal_npc_formation = "";
                            string force_npc_id = "", force_npc_formation = "";
                            string[] subs = npcid.Split(':');
                            if (subs.Length >= 2)
                            {
                                normal_npc_id = subs[0]; normal_npc_formation = subs[1];
                            }
                            subs = npc_force_id.Split(':');
                            if (subs.Length >= 2)
                            {
                                force_npc_id = subs[0]; force_npc_formation = subs[1];
                            }
                            bool force = _user._battle_free_force_token > 0;
                            if (force && force_npc_id.Length > 0)
                            {
                                target_npc_id = force_npc_id; target_npc_formation = force_npc_formation;
                            }
                            else
                            {
                                target_npc_id = normal_npc_id; target_npc_formation = normal_npc_formation;
                            }

                            // 如果征战事件NPC还有次数, 那么忽略上面的条件, 直接先打征战事件npc
                            if (_user._battle_extra_npc_id > 0 && _user._battle_extra_npc_remains > 0)
                            {
                                target_npc_id = _user._battle_extra_npc_id.ToString();
                                target_npc_formation = _user._battle_extra_npc_formation;
                            }

                            if (!last_formation.Equals(target_npc_formation))
                            {
                                if (mgr.changeFormation(_proto, _logger, target_npc_formation))
                                {
                                    attack_result = mgr.attackNpc(_proto, _logger, _user, target_npc_id, force, target_npc_formation);
                                    last_formation = target_npc_formation;
                                    solved = true;
                                }
                            }
                            else
                            {
                                attack_result = mgr.attackNpc(_proto, _logger, _user, target_npc_id, force, target_npc_formation);
                            }
                            if (attack_result == 2)
                            {
                                changeDefenseFormation(formation);
                                return _user.TokenCdTime;
                            }
                            else if (attack_result == 3)
                            {
                                changeDefenseFormation(formation);
                                return next_hour();
                            }
                            formation = last_formation;
                        }
                    }
                }
            }

            if (solved) return immediate();
            else
            {
                changeDefenseFormation(formation);
                // 检查首次
                if (attack_first_army)
                {
                    // search for troops
                    foreach (string armyid in first_army_ids)
                    {
                        if (armyid == "") continue;
                        string[] subs = armyid.Split(':');
                        if (subs.Length < 2) continue;
                        int join_result = mgr.tryFindArmy(_proto, _logger, _user, subs[0], true);
                        if (join_result == 0)
                        {
                            solved = true; break;
                        }
                        else if (join_result == 1) return 60 * 1000; // http error, 1分钟后继续
                        else if (join_result == 2)
                        {
                            if (_user.TokenCdTime > 0) return _user.TokenCdTime;
                            else return 10 * 60 * 1000; // 军令已经冷却
                        }
                        else if (join_result == 3) return next_hour(); // 没令了
                    }
                    if (solved) return immediate();
                    else return attack_first_interval * 1000;
                }
                if (armyids.Length > 0)
                {
                    if (!attack_army_only_jingyingtime || inJingyingArmyTime()) return 60 * 1000;
                    else return next_halfhour();
                }
                else return next_halfhour();
            }
        }
        private void changeDefenseFormation(string current_formation)
        {
            Dictionary<string, string> conf = getConfig();
            if (conf.ContainsKey(ConfigStrings.defense_enabled) && conf[ConfigStrings.defense_enabled].ToLower().Equals("true"))
            {
                if (conf.ContainsKey(ConfigStrings.defense_formation))
                {
                    if (!current_formation.Equals(conf[ConfigStrings.defense_formation]))
                        ServiceFactory.getBattleManager().changeFormation(_proto, _logger, conf[ConfigStrings.defense_formation]);
                }
            }
        }
    }
}
